<template>
  <div class="register-container">
    <div class="register-card">
      <div class="register-header">
        <div
          style="display: flex; align-items: center; justify-content: center"
        >
          <h1 style="margin-left: 110px">创建账号</h1>
          <span class="register-as-consultant" @click="handleRegisterAsConsultant">注册为咨询师</span>
        </div>
        <p>加入我们，开启学习之旅</p>
      </div>

      <form @submit.prevent="handleRegister" class="register-form">
        <div class="form-layout">
          <!-- 左侧头像区域 -->
          <div class="avatar-section">
            <div class="avatar-box">
              <div class="avatar-title">头像</div>
              <div class="avatar-container">
                <ImageUpload
                  v-model="formData.avatar"
                  :limit="1"
                  :style="{ width: '180px', height: '180px' }"
                  :support-file-type="['jpg', 'jpeg', 'png', 'gif']"
                  :max-size="2"
                  @change="handleAvatarChange"
                />
              </div>
            </div>
          </div>

          <!-- 右侧表单区域 -->
          <div class="form-section">
            <div class="form-row">
              <div class="form-group">
                <label for="username">用户名</label>
                <div class="input-group">
                  <i class="fas fa-user"></i>
                  <input
                    type="text"
                    id="username"
                    v-model="formData.username"
                    placeholder="请输入用户名"
                    required
                  />
                </div>
              </div>

              <div class="form-group">
                <label for="nickname">姓名</label>
                <div class="input-group">
                  <i class="fas fa-user-circle"></i>
                  <input
                    type="text"
                    id="nickname"
                    v-model="formData.nickname"
                    placeholder="请输入姓名"
                    required
                  />
                </div>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label for="gender">性别</label>
                <div class="gender-group">
                  <el-radio v-model="formData.gender" :value="0" required>
                    <span>保密</span>
                  </el-radio>
                  <el-radio v-model="formData.gender" :value="1" required>
                    <span>男</span>
                  </el-radio>
                  <el-radio v-model="formData.gender" :value="2" required>
                    <span>女</span>
                  </el-radio>
                </div>
              </div>

              <div class="form-group">
                <label for="mobile">手机号码</label>
                <div class="input-group">
                  <i class="fas fa-mobile-alt"></i>
                  <input
                    type="tel"
                    id="mobile"
                    v-model="formData.mobile"
                    placeholder="请输入手机号码"
                    required
                  />
                </div>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label for="email">邮箱</label>
                <div class="input-group">
                  <i class="fas fa-envelope"></i>
                  <input
                    type="email"
                    id="email"
                    v-model="formData.email"
                    placeholder="请输入邮箱"
                    required
                  />
                </div>
              </div>

              <div class="form-group">
                <label for="emailCode">邮箱验证码</label>
                <div class="input-group code-group">
                  <i class="fas fa-shield-alt"></i>
                  <input
                    type="text"
                    id="emailCode"
                    v-model="formData.emailCode"
                    placeholder="请输入验证码"
                    required
                  />
                  <button
                    type="button"
                    class="code-button"
                    :disabled="
                      !formData.email ||
                      !isValidEmail ||
                      countdown > 0 ||
                      emaiLoading
                    "
                    @click="handleSendCode"
                  >
                    <i v-if="emaiLoading" class="el-icon loading">
                      <svg class="circular" viewBox="25 25 50 50">
                        <circle
                          class="path"
                          cx="50"
                          cy="50"
                          r="20"
                          fill="none"
                        />
                      </svg>
                    </i>
                    <span v-else>
                      {{
                        countdown > 0 ? `${countdown}秒后重试` : "获取验证码"
                      }}
                    </span>
                  </button>
                </div>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label for="school">就读/毕业学校</label>
                <div class="input-group">
                  <el-select
                    v-model="formData.schoolId"
                    placeholder="请选择学校"
                  >
                    <el-option
                      v-for="school in schoolList"
                      :key="school.id"
                      :label="school.name"
                      :value="school.id"
                    />
                  </el-select>
                </div>
              </div>

              <div class="form-group">
                <label for="academicDegree">学历</label>
                <div class="input-group">
                  <el-select
                    v-model="formData.academicDegreeCode"
                    placeholder="请选择学历"
                  >
                    <el-option
                      v-for="degree in academicDegreeList"
                      :key="degree.value"
                      :label="degree.label"
                      :value="degree.value"
                    />
                  </el-select>
                </div>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label for="password">密码</label>
                <div class="input-group">
                  <i class="fas fa-lock"></i>
                  <input
                    :type="showPassword ? 'text' : 'password'"
                    id="password"
                    v-model="formData.password"
                    placeholder="请输入密码"
                    required
                  />
                  <i
                    class="fas"
                    :class="showPassword ? 'fa-eye-slash' : 'fa-eye'"
                    @click="togglePasswordVisibility"
                  ></i>
                </div>
                <div class="password-strength" v-if="formData.password">
                  <div
                    class="strength-bar"
                    :class="passwordStrengthClass"
                  ></div>
                  <span class="strength-text">{{ passwordStrengthText }}</span>
                </div>
              </div>

              <div class="form-group">
                <label for="confirmPassword">确认密码</label>
                <div class="input-group">
                  <i class="fas fa-lock"></i>
                  <input
                    :type="showConfirmPassword ? 'text' : 'password'"
                    id="confirmPassword"
                    v-model="confirmPassword"
                    placeholder="请再次输入密码"
                    required
                  />
                  <i
                    class="fas"
                    :class="showConfirmPassword ? 'fa-eye-slash' : 'fa-eye'"
                    @click="toggleConfirmPasswordVisibility"
                  ></i>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="form-footer">
          <div class="form-group agreement-group">
            <label class="agreement">
              <div style="display: flex; align-items: center">
                <input
                  type="checkbox"
                  v-model="agreement"
                  required
                  style="margin-right: 10px"
                />
                <span>我已阅读并同意</span>
                <a href="#" class="terms-link">《用户协议》</a>
                <span>和</span>
                <a href="#" class="terms-link">《隐私政策》</a>
              </div>
            </label>
          </div>

          <button
            type="submit"
            class="register-button"
            :disabled="loading || !agreement"
            @click="handleRegister"
          >
            <span v-if="loading" class="loading-spinner"></span>
            {{ loading ? "注册中..." : "立即注册" }}
          </button>

          <div class="login-link">
            已有账号？
            <router-link to="/login">立即登录</router-link>
          </div>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import {
  requestUserRegister,
  type SingInForm,
  sendVerificationCode,
} from "@/api/user";
import { querySchoolList, type SchoolType } from "@/api/school";
import { getDictList, type DictItem } from "@/api/dict";
import ImageUpload from "@/components/ImageUpload.vue";

const router = useRouter();
const loading = ref(false);
const showPassword = ref(false);
const showConfirmPassword = ref(false);
const agreement = ref(false);
const confirmPassword = ref("");
const avatarUrl = ref("");
const avatarFile = ref<File | null>(null);

const formData = ref<SingInForm>({
  username: "",
  nickname: "",
  mobile: "",
  email: "",
  emailCode: "",
  gender: 1,
  password: "",
  avatar: "",
  roleIds: [1],
});

const countdown = ref(0);
let timer: number | undefined;

// 验证邮箱格式
const isValidEmail = computed(() => {
  return /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(
    formData.value.email || ""
  );
});

const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};

const toggleConfirmPasswordVisibility = () => {
  showConfirmPassword.value = !showConfirmPassword.value;
};

const passwordStrength = computed(() => {
  const password = formData.value.password;
  if (!password) return 0;

  let strength = 0;
  if (password.length >= 8) strength += 1;
  if (/[A-Z]/.test(password)) strength += 1;
  if (/[0-9]/.test(password)) strength += 1;
  if (/[^A-Za-z0-9]/.test(password)) strength += 1;

  return strength;
});

const passwordStrengthClass = computed(() => {
  const strength = passwordStrength.value;
  if (strength <= 1) return "weak";
  if (strength <= 2) return "medium";
  return "strong";
});

const passwordStrengthText = computed(() => {
  const strength = passwordStrength.value;
  if (strength <= 1) return "弱";
  if (strength <= 2) return "中";
  return "强";
});

const handleAvatarChange = (url: string) => {
  formData.value.avatar = url;
};

const validateForm = () => {
  if (!/^[a-zA-Z0-9]+$/.test(formData.value.username)) {
    ElMessage.warning("用户名只能是字母和数字");
    return false;
  }
  if (!formData.value.username) {
    ElMessage.warning("请输入用户名");
    return false;
  }
  if (!formData.value.nickname) {
    ElMessage.warning("请输入昵称");
    return false;
  }
  if (!formData.value.mobile) {
    ElMessage.warning("请输入手机号码");
    return false;
  }
  if (!/^1[3-9]\d{9}$/.test(formData.value.mobile)) {
    ElMessage.warning("请输入正确的手机号码");
    return false;
  }
  if (!formData.value.email) {
    ElMessage.warning("请输入邮箱");
    return false;
  }
  if (!isValidEmail.value) {
    ElMessage.warning("请输入正确的邮箱格式");
    return false;
  }
  if (!formData.value.emailCode) {
    ElMessage.warning("请输入邮箱验证码");
    return false;
  }
  if (!formData.value.avatar) {
    ElMessage.warning("请上传头像");
    return false;
  }
  if (!formData.value.password) {
    ElMessage.warning("请输入密码");
    return false;
  }
  if (formData.value.password.length < 8) {
    ElMessage.warning("密码长度不能少于8位");
    return false;
  }
  if (formData.value.password !== confirmPassword.value) {
    ElMessage.warning("两次输入的密码不一致");
    return false;
  }
  if (!agreement.value) {
    ElMessage.warning("请阅读并同意用户协议和隐私政策");
    return false;
  }
  return true;
};

const schoolList = ref<SchoolType[]>([]);
const getAllSchools = async () => {
  const res = await querySchoolList();
  schoolList.value = res;
};
const academicDegreeList = ref<DictItem[]>([]);
const getAcademicDegreeList = async () => {
  const res = await getDictList("academic_degree");
  academicDegreeList.value = res;
};
onMounted(async () => {
  await getAllSchools();
  await getAcademicDegreeList();
});
const emaiLoading = ref(false);
// 发送验证码
const handleSendCode = async () => {
  if (!formData.value.email || !isValidEmail.value) {
    ElMessage.warning("请输入正确的邮箱格式");
    return;
  }

  try {
    emaiLoading.value = true;
    const res = await sendVerificationCode(formData.value.email, "EMAIL");
    if (res) {
      ElMessage.success("验证码已发送，请查收邮件");
      // 开始倒计时
      countdown.value = 60;
      timer = setInterval(() => {
        if (countdown.value > 0) {
          countdown.value--;
        } else {
          clearInterval(timer);
        }
      }, 1000);
    }
  } catch (error) {
    console.error("发送验证码失败:", error);
  } finally {
    emaiLoading.value = false;
  }
};

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});
const handleRegisterAsConsultant = () => {
  router.push("/register-consultant");
};
const handleRegister = async () => {
  if (!validateForm()) return;

  try {
    loading.value = true;
    formData.value.schoolName = schoolList.value.find(
      (item) => item.id === formData.value.schoolId + ""
    )?.name;
    formData.value.academicDegreeName = academicDegreeList.value.find(
      (item) => item.value === formData.value.academicDegreeCode
    )?.label;

    formData.value.roleIds = [3];
    formData.value.isConsultant = false;
    formData.value.deptId = 1;

    // 调用注册API
    const res = await requestUserRegister(formData.value);
    console.log(res, "res");
    if (res) {
      router.push("/login");
      ElMessage.success("注册成功，请登录");
    } else {
      ElMessage.error("注册失败，请稍后重试");
    }
  } catch (error) {
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f0f2f5;
  padding: 20px;
}

.register-card {
  width: 100%;
  max-width: 900px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  padding: 40px;
}

.register-header {
  text-align: center;
  margin-bottom: 40px;
}

.register-header h1 {
  font-size: 28px;
  color: #1a1a1a;
  margin-bottom: 12px;
  font-weight: 600;
}

.register-header p {
  color: #666;
  font-size: 16px;
}

.form-layout {
  display: grid;
  grid-template-columns: 250px 1fr;
  gap: 40px;
  margin-bottom: 30px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-box {
  border: 2px solid #eee;
  border-radius: 8px;
  padding: 20px;
  width: 100%;
}

.avatar-title {
  font-size: 16px;
  font-weight: 500;
  color: #1a1a1a;
  text-align: center;
  margin-bottom: 20px;
}

.avatar-container {
  display: flex;
  justify-content: center;
}

.form-section {
  flex: 1;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-bottom: 16px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #1a1a1a;
  font-weight: 500;
  font-size: 14px;
  text-align: left;
}

.input-group {
  position: relative;
  display: flex;
  align-items: center;
}

.input-group i {
  position: absolute;
  left: 12px;
  color: #999;
  font-size: 16px;
  z-index: 1;
}

.input-group input {
  width: 100%;
  height: 40px;
  padding: 8px 12px 8px 36px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s;
  background: #f9fafb;
}

.input-group input:focus {
  background: white;
  border-color: #1890ff;
  box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.1);
  outline: none;
}

.input-group i:last-child {
  right: 12px;
  left: auto;
  cursor: pointer;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-input__wrapper) {
  background: #f9fafb;
  border-radius: 8px;
  height: 40px;
  padding: 0 12px;
}

:deep(.el-input__wrapper.is-focus) {
  background: white;
  box-shadow: 0 0 0 1px #1890ff;
}

.password-strength {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.strength-bar {
  flex: 1;
  height: 4px;
  border-radius: 2px;
  background: #eee;
  overflow: hidden;
}

.strength-bar::after {
  content: "";
  display: block;
  height: 100%;
  width: 0;
  transition: width 0.3s;
}

.strength-bar.weak::after {
  width: 33%;
  background: #ff4d4f;
}

.strength-bar.medium::after {
  width: 66%;
  background: #faad14;
}

.strength-bar.strong::after {
  width: 100%;
  background: #52c41a;
}

.strength-text {
  font-size: 12px;
  color: #666;
}

.gender-group {
  display: flex;
  gap: 20px;
  align-items: center;
  height: 40px;
  padding: 0 8px;
}

.form-footer {
  border-top: 1px solid #f0f0f0;
  padding-top: 24px;
}

.agreement-group {
  margin-bottom: 24px;
}

.agreement {
  display: flex;
  align-items: center;
  color: #666;
  cursor: pointer;
  font-size: 14px;
}

.terms-link {
  color: #1890ff;
  text-decoration: none;
  margin: 0 4px;
}

.terms-link:hover {
  text-decoration: underline;
}

.register-button {
  width: 100%;
  height: 44px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
}

.register-button:hover {
  background-color: #40a9ff;
}

.register-button:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: white;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.login-link {
  margin-top: 24px;
  text-align: center;
  color: #666;
  font-size: 14px;
}

.login-link a {
  color: #1890ff;
  text-decoration: none;
  font-weight: 500;
}

.login-link a:hover {
  text-decoration: underline;
}

@media (max-width: 768px) {
  .register-card {
    padding: 24px;
  }

  .form-layout {
    grid-template-columns: 1fr;
    gap: 30px;
  }

  .form-row {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .avatar-box {
    max-width: 250px;
    margin: 0 auto;
  }
}

.code-group {
  position: relative;
}

.code-button {
  position: absolute;
  right: 1px;
  top: 1px;
  bottom: 1px;
  padding: 0 12px;
  font-size: 14px;
  background: #f0f0f0;
  border: none;
  border-radius: 0 8px 8px 0;
  color: #1890ff;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.3s;
  min-width: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.code-button:hover:not(:disabled) {
  background: #e6f7ff;
}

.code-button:disabled {
  color: #999;
  cursor: not-allowed;
  background: #f5f5f5;
}

.loading {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
}

.circular {
  width: 20px;
  height: 20px;
  animation: loading-rotate 2s linear infinite;
}

.path {
  stroke-dasharray: 90, 150;
  stroke-dashoffset: 0;
  stroke-width: 2;
  stroke: #1890ff;
  stroke-linecap: round;
  animation: loading-dash 1.5s ease-in-out infinite;
}

@keyframes loading-rotate {
  100% {
    transform: rotate(360deg);
  }
}

@keyframes loading-dash {
  0% {
    stroke-dasharray: 1, 200;
    stroke-dashoffset: 0;
  }
  50% {
    stroke-dasharray: 90, 150;
    stroke-dashoffset: -40px;
  }
  100% {
    stroke-dasharray: 90, 150;
    stroke-dashoffset: -120px;
  }
}

.input-group input:not(:last-child) {
  padding-right: 100px;
}
.register-as-consultant {
  font-size: 17px;
  color: #666;
  cursor: pointer;
  text-decoration: underline;
  margin-left: 10px;
}
.register-as-consultant:hover {
  color: #1890ff;
}
</style>
